/**
 * Created by scenic on 2017/8/10.
 */
import {Plank} from "./Plank";
function SpaceFace(host, name) {
    THREE.Plane.call(this)
    this.geometryFaces = [];
    this.name = name;
    this.hostSpace = host;
    this.box3 = new THREE.Box3();
    this.associatePlank = new Plank(this);
    this.isAddToScene = false;
}

SpaceFace.prototype = Object.assign(Object.create(THREE.Plane.prototype), {
    constructor: SpaceFace,

    initialize: function (face1, face2, vertices, matrixWorld) {
        this.box3.setFromPoints([
            vertices[face1.a].clone().applyMatrix4(matrixWorld),
            vertices[face1.b].clone().applyMatrix4(matrixWorld),
            vertices[face1.c].clone().applyMatrix4(matrixWorld),
            vertices[face2.a].clone().applyMatrix4(matrixWorld),
            vertices[face2.b].clone().applyMatrix4(matrixWorld),
            vertices[face2.c].clone().applyMatrix4(matrixWorld),
        ]);
        this.geometryFaces[0] = face1;
        this.geometryFaces[1] = face2;
        this.setFromNormalAndCoplanarPoint(face2.normal, this.box3.min);
    },

    updatePlankByBaseGraphic: function () {
        var up = new THREE.Vector3(0, 1, 0);

        var normal = this.normal;
        var mesh = this.associatePlank.plankMesh;
        var size = this.box3.getSize().addScaledVector(normal, this.associatePlank.thickness).positive();
        var quaternion = new THREE.Quaternion().setFromUnitVectors(up, normal);
        mesh.quaternion.set(0, 0, 0, 1).copy(quaternion);
        mesh.position.copy(this.box3.getCenter()).addScaledVector(normal.clone().negate(), this.associatePlank.thickness / 2);
        mesh.scaleToDimension(size.applyQuaternion(quaternion).positive())
    },

    //UI交互中被调用
    onClick: function (scene) {
        //确保mesh被创建，同时增加到场景中
        scene.add(this.getAssociateMesh());
        this.getAssociateMesh().isAddToScene = true;

        this.hostSpace.getRoot().traverse(function (s) {
            s.updateSegment();
            s.updatePlankDimensionWidthDefault();
            s.updatePlankDoor();
            s.updateSpaceMeshMaterial();
            s.updateSegment();
        })

    },

    getAssociateMesh: function () {
        return this.associatePlank.plankMesh;
    },
    getAssociateThickness: function () {
        if (!this.getAssociateMesh().isAddToScene) {
            return 0;
        }/*else if(this.associatePlank.isDoor) {
         return 0;
         } */ else {
            return this.associatePlank.thickness;
        }
    },

    getNormal: function () {
        return this.geometryFaces[0].normal;
    },
    getCenter: function () {
        return this.box3.getCenter();
    }
})
export {SpaceFace}